package com.lhl.api.conver;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @className: LocalDateJsonFormat
 * @description: java8日期序列化和反序列化
 * @author: king
 * @date: 2020-09-10 9:19
 **/
@JsonComponent
@Slf4j
public class LocalDateJsonFormat {
    /**
     * 对象转换成字符串
     */
    public static class DateTimeSerializer extends JsonSerializer<LocalDateTime> {
        @Override
        public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(LocalDateTimeUtil.format(localDateTime, DatePattern.NORM_DATETIME_PATTERN));
        }
    }

    /**
     * 解析日期字符串
     */
    public static class DateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
        @Override
        public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            if (StrUtil.isNotBlank(jsonParser.getText())) {
                return LocalDateTimeUtil.parse(jsonParser.getText());
            }
            return null;
        }
    }

    public static class DateSerializer extends JsonSerializer<LocalDate> {
        @Override
        public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeString(LocalDateTimeUtil.format(localDate,DatePattern.NORM_DATE_FORMATTER));
        }
    }


    public static class DateDeserializer extends JsonDeserializer<LocalDate> {
        @Override
        public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            if (StrUtil.isNotBlank(jsonParser.getText())) {
                return LocalDateTimeUtil.parseDate(jsonParser.getText());
            }
            return null;
        }
    }
}